export default {
    namespace: 'message',
    state: {
        // list:[{
        //     id:1,
        //     content:'横眉冷对千夫指,俯首甘为孺子牛',
        //     date:new Date().toLocaleDateString()
        // },
        // {
        //     id:2,
        //     content:'忽如一夜春风来,千树万树梨花开',
        //     date:new Date().toLocaleDateString()
        // }]
        list: []
    },
    reducers: {
        add(state, action) {
            const id=state.list.length>0?state.list[0].id+1:1;
            const msg={
                id,
                ...action.data,
                date:new Date().toLocaleDateString()
            }
            console.log(msg);
            let newMsg=[...state.list];
            newMsg.unshift(msg);
            return {...state,list:newMsg};
        },
        del(state, action) {
            const arr = state.list.filter((item) => {
                return item.id !== action.data;
            });
            return { ...state, list: arr }
        },
        getList(state, action) {
            return { ...state, list: action.data };
        }
    },
    // 异步操作, 需要通过generator函数来实现
    effects: {
        *getListAsync(action, { call, put }) {
            // call用来调用方法, put用来触发action
            yield call(delay, 2000);
            let list = [{
                id: 2,
                content: '横眉冷对千夫指,俯首甘为孺子牛',
                date: new Date().toLocaleDateString()
            },
            {
                id: 1,
                content: '忽如一夜春风来,千树万树梨花开',
                date: new Date().toLocaleDateString()
            }];

            yield put({ type: 'getList', data: list });

        }
    },
    // 消息订阅
    subscriptions: {
        setup({ dispatch, history }) {  // eslint-disable-line
            console.log('消息订阅');
        }
    },
}

// 工具函数
function delay(timeout) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);
    });
}